// import { useStore } from '@/stores/counter'
let ids: number | string = 0
// const store = useStore()
let closes:any
export let close:any=()=>{
    closes.close()
    useWebSocketClass.instance=null
}
 class useWebSocketClass {
    static instance: useWebSocketClass
    ws: WebSocket = new WebSocket(`ws://47.106.157.197:8081/websocket/${ids}`)
    effect: Map<string, Function> = new Map()
    constructor(name: string, message: Function) {
        //单列模式

        
        if (!useWebSocketClass.instance) {
            this.init()
            useWebSocketClass.instance = this
        }
        useWebSocketClass.instance.effect.set(name, message)
        return useWebSocketClass.instance
    }
    Open() {
        console.log('连接成功');
        closes= useWebSocketClass.instance.ws
    }
    Close() {
        console.log('连接关闭');
    }
    Error() {
        console.log("连接失败");
    }
    //清除依赖
    deleteEffect(name: string) {
        useWebSocketClass.instance.effect.delete(name)
    }
    //当后端传来消息时将通知给到依赖
    Message(e: any) {

        useWebSocketClass.instance.effect.forEach((element) => {
            element(JSON.parse(e.data))
        })
        console.log(11);
        
    }
    init() {
        this.ws.addEventListener('open', this.Open, false)
        this.ws.addEventListener('message', this.Message, false)
        this.ws.addEventListener('close', this.Close, false)
        this.ws.addEventListener('error', this.Error, false)
    }
}

export function useWebSocket(name: string, Message: Function, id?: string | number): WebSocket {
    console.log('我被调用了');
    if (id) {
        ids = id
    }
     ws= new useWebSocketClass(name, Message).ws
     return ws
}
export let ws:any


